import { getServer, isLogin } from '/store/mutations'
import { userApi } from '/api/user'
import { topicApi } from '/api/topic'
import { feedApi } from '/api/feed'
import { knowledgeApi } from '/api/konwledge'
import { mallApi } from '/api/mall'
import { $event, $utils } from '/utils'
import { GlobalData } from '/store/state'
import { activityApi } from '/api/activity'
import { knowAboutApi } from '/api/knowAbout'
import { checkAuth } from '/store/actions'

Page({
  data: {
    user: { name: ' ' } as DomoUser,
    users: {} as DomoUser,
    feeds: [] as DomoFeed[],
    topics: [] as DomoTopic[],
    commodities: [] as DomoCommodity[],
    knowAbout: [] as DomoKnowAbout[],
    knowledge: [],
    currentUser: true,
    query: {
      limit: 15 as number,
      after: 0 as number,
      user: 0 as number,
      type: 'users',
      loading: false,
    },
    cQuery: {
      loading: false,
      page: 1,
      limit: 10,
      user_id: 0 as number,
      order: 'topped_at desc, updated_at desc',
      with: 'brands',
    },
    kQuery: {
      loading: false,
      page: 1,
      limit: 10,
      author_id: 0 as number,
      status: '0,1',
      liked: 'check',
      order: 'topped_at desc, updated_at desc',
    },
    eQuery: {
      loading: false,
      offset: 0,
      limit: 10,
      user_id: 0 as number,
    },
    wQuery: {
      loading: false,
      offset: 0,
      limit: 10,
      author_id: 0 as number,
      order: 'comments_count',
      firstAnswer: true,
    },
    commodityLoaded: false,
    commodityCanLoad: true,
    knowledgeCanLoad: true,
    knowledgeLoaded: false,
    knowAboutCanLoad: true,
    knowAboutLoaded: false,
    eventCanLoad: true,
    eventLoaded: false,
    scrollClass: false,
    feedCanLoad: true,
    currentTab: 0,
    currencyName: GlobalData.currencyName,
    navigationHeight: GlobalData.navigationHeight,
    paytoast: false,
    topic: {} as DomoTopic,
    events: [] as Activity[],
    /** 活动锁 */
    wantJoin: false,
    tags: [],
    create_permission: '',
    canCreate: false,
    /** 是否当前登录用户 */
    currentUse: false,
    id: 0,
    userAbilities: GlobalData.userAbilities,
    itemList: [] as string[],
    topicsNum: 0,
  },
  onLoad(query: any) {
    let { id } = query
    if (query.scene) {
      const scene = $utils.parseQueryString(query.scene)
      id = scene.id
    }
    this.setData({ id: parseInt(id) })
    $event.on('after:changeFeedList', this, () => {
      this.fetchFeeds(this.data.id)
    })
    this.fetchFeeds(id)
    this.init()
    this.fetchTopics(id)
    $event.on('after:boot', this, () => {
      this.setData({
        currencyName: GlobalData.currencyName,
        access: GlobalData.access,
        navigationHeight: GlobalData.navigationHeight,
      })
    })
    this.setData!({
      currencyName: GlobalData.currencyName,
      access: GlobalData.access,
      navigationHeight: GlobalData.navigationHeight,
      userAbilities: GlobalData.userAbilities,
    })
    $event.on('after:joinTopic', this, (topic: DomoTopic) => {
      this.changeTopic(topic)
    })
    $event.on('activityChange', this, (event: Activity) => {
      this.changeEvents(event)
    })
    $event.on('after:deleteTopic', this, (topic: DomoTopic) => {
      this.deleteTopic(topic)
    })
    $event.on('erorr:integral', this, ({ paytoast, topic }) => {
      this.setData({
        paytoast,
        topic,
      })
    })
    $event.on('after:login', this, this.init)
    $event.on('shopDownStateUpdate', this, (commondity) => {
      this.data.commodities.forEach((element) => {
        if (element.id === commondity.id) {
          element.deleted_at = commondity.deleted_at
        }
      })
      this.setData({ commodities: this.data.commodities })
    })
    this.resolveCreateTopic()
  },
  onUnload() {
    $event.off('shopDownStateUpdate', this)
  },
  init() {
    const { id } = this.data
    const server = getServer()
    const user = wx.getStorageSync(`${server}/logged`).data || {}
    const users = user
    // 非当前登录用户
    if (user.id !== id) {
      this.setData({
        currentUser: false,
        users,
      })
      this.fetchUserInfo(id)
    } else {
      // 当前登录用户
      this.setData({
        currentUse: true,
        user,
        users,
        query: {
          ...this.data.query,
          user: id,
        },
      })
      this.fetchUserInfo(id)
    }
  },
  onPageScroll() {
    this.fixedTitle()
  },
  /** 获取编辑列表 */
  editList() {
    const {
      data: { userAbilities, user },
    } = this
    const itemList = [] as string[]
    if (userAbilities && userAbilities.some((v: any) => v.name === '[user] Disabled User')) {
      itemList.push('禁用')
    } else {
      itemList.push('举报')
      itemList.push(user.blacked ? '移出黑名单' : '加入黑名单')
    }
    this.setData({
      itemList,
    })
  },
  /** 操作更多 */
  edit() {
    this.editList()
    const {
      data: { itemList, user },
    } = this
    wx.showActionSheet({
      itemList,
      success: ({ tapIndex }) => {
        const item = itemList[tapIndex]
        if (item === '举报') {
          wx.navigateTo({
            url: `/pages/report/report?type=user&id=${user.id}`,
          })
          return
        } else {
          const method =
            item === '禁用'
              ? 'deleteUser'
              : item === '取消禁用'
              ? 'deleteUserUp'
              : item === '加入黑名单'
              ? 'black'
              : 'unBlack'
          userApi[method](user.id)
            .then(() => {
              if (item.includes('黑名单')) {
                this.setData({
                  user: { ...user, blacked: !user.blacked },
                })
              }
              wx.showToast({
                title: `已成功${item}`,
              })
              this.init()
            })
            .catch(() => {
              wx.showToast({
                title: `${item}失败`,
                icon: 'none',
              })
            })
        }
      },
    })
  },
  /** 判断是否滚动到了点评 */
  fixedTitle() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#title').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollClass: res[0] ? res[0].top < this.data.navigationHeight : true,
      })
    })
  },
  resolveCreateTopic() {
    const {
      data: { user },
    } = this
    topicApi.getTopicConfig().then((data: TopicConfig) => {
      const {
        config: { create_permission, permission },
      } = data
      const abilities: any = GlobalData.userAbilities
      this.setData({
        create_permission,
        canCreate:
          create_permission === 'all'
            ? true
            : create_permission === 'verification' &&
              user &&
              user.verification &&
              user.verification.state === 1
            ? true
            : create_permission === 'specialUser' &&
              abilities &&
              abilities.some((v: any) => v.name === permission)
            ? true
            : false,
      })
    })
  },
  // 触底加载更多
  async onReachBottom() {
    const {
      data: { currentTab },
    } = this
    if (currentTab == 0) {
      this.fetchFeeds(this.data.query.user, true)
    }
    if (currentTab == 1) {
      this.getUserCommodities(this.data.query.user, true)
    }
    if (currentTab == 2) {
      this.fetchKnowledge(this.data.query.user, true)
    }
    if (currentTab == 3) {
      this.fetchEvents(this.data.query.user, true)
    }
    if (currentTab == 4) {
      this.fetchknowAbout(this.data.query.user, true)
    }
  },
  // 获取用户信息
  async fetchUserInfo(user_id: number) {
    const user = await userApi.getUser(user_id)
    const tags = await userApi.getSomeoneTags(user_id)
    this.setData({
      user,
      tags,
      query: {
        ...this.data.query,
        user: user_id,
      },
    })
  },
  /** 获取当前用户的活动库 */
  fetchEvents(author_id: number, loadMore = false) {
    const {
      data: { eQuery, eventCanLoad },
    } = this
    if (eQuery.loading) return
    eQuery.user_id = author_id
    // 加载更多的情况，需要判断是否能再加载
    if (loadMore) {
      if (!eventCanLoad) return
      eQuery.offset = $utils.getLastField(this.data.events)
    }
    // 设置加载状态
    this.setData({
      eQuery: {
        ...this.data.eQuery,
        loading: true,
      },
    })
    activityApi
      .getActivityList(eQuery)
      .then((data) => {
        this.setData({
          // 设置知识列表的数据
          events: loadMore ? [...this.data.events, ...data] : data,
          eQuery,
          eventCanLoad: data.length === eQuery.limit,
          // 设置已经加载
          eventLoaded: true,
        })
      })
      .catch((res) => {
        console.log(res)
      })
  },
  /** 获取当前用户的知识库 */
  fetchKnowledge(author_id: number, loadMore = false) {
    const {
      data: { kQuery, knowledgeCanLoad },
    } = this
    if (kQuery.loading) return
    kQuery.author_id = author_id
    // 加载更多的情况，需要判断是否能再加载
    if (loadMore) {
      if (!knowledgeCanLoad) return
      kQuery.page += 1
    }
    // 设置加载状态
    this.setData({
      kQuery: {
        ...this.data.kQuery,
        loading: true,
      },
    })
    knowledgeApi
      .getKnowledge(kQuery)
      .then((data) => {
        this.setData({
          // 设置知识列表的数据
          knowledge: loadMore ? [...this.data.knowledge, ...data.data] : data.data,
          kQuery,
          knowledgeCanLoad: data.data.length === kQuery.limit,
          // 设置已经加载
          knowledgeLoaded: true,
        })
      })
      .catch((res) => {
        console.log(res)
      })
  },
  /** 获取当前用户的提问 */
  fetchknowAbout(author_id: number, loadMore = false) {
    const {
      data: { wQuery, knowAboutCanLoad },
    } = this
    if (wQuery.loading) return
    wQuery.author_id = author_id
    // 加载更多的情况，需要判断是否能再加载
    if (loadMore) {
      if (!knowAboutCanLoad) return
      wQuery.offset = $utils.getLastField(this.data.knowAbout)
    }
    // 设置加载状态
    this.setData({
      wQuery: {
        ...this.data.wQuery,
        loading: true,
      },
    })
    knowAboutApi
      .getKnowAboutList(wQuery)
      .then((data) => {
        this.setData({
          // 设置问答列表的数据
          knowAbout: loadMore ? [...this.data.knowAbout, ...data] : data,
          wQuery,
          knowAboutCanLoad: data.length === wQuery.limit,
          // 设置已经加载
          knowAboutLoaded: true,
        })
      })
      .catch((res) => {
        console.log(res)
      })
  },
  // 获取动态
  async fetchFeeds(user_id: number, loadMore = false) {
    const {
      data: { query },
    } = this as any
    if (query.loading) return
    query.user = user_id
    if (loadMore) {
      if (!this.data.feedCanLoad) return
    }
    ;(query.after = loadMore ? $utils.getLastField(this.data.feeds) : 0),
      this.setData({
        query: {
          ...this.data.query,
          loading: true,
        },
      })
    const feeds = await feedApi.getFeeds(query)
    this.setData({
      query: {
        ...this.data.query,
        loading: false,
      },
      feedCanLoad: feeds.length === query.limit,
      feeds: loadMore ? [...this.data.feeds, ...feeds] : feeds,
    })
  },
  // tab切换
  clickTab(e: any) {
    if (this.data.currentTab === e.target.dataset.current) {
      return false
    } else {
      this.setData(
        {
          currentTab: e.target.dataset.current,
        },
        () => {
          if (e.target.dataset.current == 1) {
            const {
              data: { commodityLoaded },
            } = this
            if (!commodityLoaded) {
              this.getUserCommodities(this.data.query.user)
            }
          }
          if (e.target.dataset.current == 2) {
            const {
              data: { knowledgeLoaded },
            } = this
            if (!knowledgeLoaded) {
              this.fetchKnowledge(this.data.query.user)
            }
          }
          if (e.target.dataset.current == 3) {
            const {
              data: { eventLoaded },
            } = this
            if (!eventLoaded) {
              this.fetchEvents(this.data.query.user)
            }
          }
          if (e.target.dataset.current == 4) {
            const {
              data: { knowAboutLoaded },
            } = this
            if (!knowAboutLoaded) {
              this.fetchknowAbout(this.data.query.user)
            }
          }
        },
      )
    }
    return false
  },
  // 处理关注操作
  resolveFollow(e: any) {
    const {
      target: {
        dataset: {
          user: { id, has_follower },
        },
      },
    } = e
    if (!isLogin()) {
      return checkAuth()
    }
    // 如果关注了
    if (!has_follower) {
      userApi.followUser(id).then(() => {
        this.setData({
          user: {
            ...this.data.user,
            has_follower: !has_follower,
          },
        })
      })
    } else {
      userApi.unFollowUser(id).then(() => {
        this.setData({
          user: {
            ...this.data.user,
            has_follower: !has_follower,
          },
        })
      })
    }
    return
  },
  // 获取话题
  fetchTopics(user_id: number) {
    topicApi
      .getUserTopics({
        direction: 'desc',
        for_user: user_id,
        limit: 3,
        status: this.data.currentUse ? 'all' : 'passed',
      })
      .then((data: DomoTopic[]) => {
        this.setData({
          topics: data,
        })
      })
    userApi.getTopicsNum({ user_id }).then(({ topics_total, passed_topics_count }) => {
      this.setData({
        topicsNum: this.data.currentUser ? topics_total : passed_topics_count,
      })
    })
  },
  // 跳转到话题
  goToDetail(e: any) {
    const {
      target: {
        dataset: { topic },
      },
    } = e
    if (topic) {
      wx.navigateTo({ url: `/pages/topic/detail/detail?topicId=${topic.id}` })
      return
    }
    $event.emit('download')
  },
  // 跳转到商品
  toDetail(event: WechatMiniprogram.BaseEvent) {
    const data = event.currentTarget.dataset as { commodityId: number }
    wx.navigateTo({ url: `/mall/detail/detail?commodityId=${data.commodityId}` })
  },
  toCreateTopic() {
    const {
      data: { canCreate, create_permission },
    } = this
    if (!canCreate) {
      wx.showModal({
        title: '提示',
        content:
          create_permission === 'verification'
            ? '认证用户才能创建圈子'
            : '无法创建圈子，请联系管理员',
      })
      return
    }
    wx.navigateTo({ url: '/mine/create-topic/create-topic' })
  },
  toTopicList() {
    const {
      data: {
        user: { id },
      },
    } = this
    wx.navigateTo({ url: `/mine/topics/topics?user=${id}` })
  },
  // 获取用户的商品
  async getUserCommodities(user_id: number, loadMore = false) {
    const {
      data: {
        query: { user },
        cQuery,
        commodityCanLoad,
      },
    } = this
    if (cQuery.loading) return
    cQuery.user_id = user
    // 加载更多
    if (loadMore) {
      // 已无法加载更多
      if (!commodityCanLoad) {
        return
      }
      cQuery.page += 1
    }
    this.setData({
      cQuery: {
        ...this.data.cQuery,
        loading: true,
      },
    })
    const { data = [] as DomoCommodity[] } = await mallApi.getCommodities(cQuery)
    this.setData({
      commodities: loadMore ? [...this.data.commodities, ...data] : data,
      commodityCanLoad: data.length === cQuery.limit,
      commodityLoaded: true,
      cQuery,
    })
  },
  /** 缓存改变状态 */
  changeTopic(topic: DomoTopic) {
    const topics = this.data.topics
    topics[topics.findIndex((i: any) => i.id === topic.id)] = topic
    this.setData({
      topics,
    })
  },
  /** 删除圈子时改变缓存 */
  deleteTopic(topic: DomoTopic) {
    const topics = this.data.topics
    topics.splice(
      topics.findIndex((i: any) => i.id === topic.id),
      1,
    )
    this.setData({
      topics,
    })
  },
  /** 活动详情 */
  todetail(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { id },
      },
    } = e
    wx.navigateTo({
      url: `/pages/activity/detail/detail?id=${id}`,
    })
  },
  /** 加入/取消加入 */
  async join(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { item, index },
      },
    } = e
    if (this.data.wantJoin || item.wantJoin) {
      wx.showToast({
        title: '您已加入过了哟',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    this.setData({
      wantJoin: true,
    })
    await activityApi.wantJoinActivity(+item.id)
    this.data.events[index].wantJoin = true
    this.changeEvents(this.data.events[index])
    this.setData({
      wantJoin: false,
    })
    wx.showToast({
      title: '加入成功',
      icon: 'none',
      duration: 1000,
    })
  },
  /** 改变活动状态 */
  changeEvents(event = {} as Activity) {
    const events = this.data.events
    events[events.findIndex((i: any) => i.id === event.id)] = event
    this.setData({
      events,
    })
  },
  onShareAppMessage() {
    this.setData({
      share: true,
    })
    return {
      path: $utils.getSharePath(),
    }
  },
  /** 聊天 */
  toChat() {
    const {
      data: { user, users },
    } = this
    if (!isLogin()) {
      return checkAuth()
    }
    if (Object.keys(user).length == 0) {
      return
    }
    wx.navigateTo({
      url: `/pages/news/chatroom/chatroom?username=${JSON.stringify({
        your: GlobalData.imVersion + '' + user.id,
        myName: GlobalData.imVersion + '' + users.id,
        name: users.name,
        yourname: user.name,
      })}`,
    })
    return
  },
})
